package org.nf.vrs.userservice.service;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.nf.vrs.userservice.dao.RoleDao;
import org.nf.vrs.userservice.dto.RoleDTO;
import org.nf.vrs.userservice.entity.Role;
import org.nf.vrs.userservice.inf.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author duang
 * @date 2022/3/30
 */
@Slf4j
@Transactional(rollbackFor = RuntimeException.class)
@DubboService(interfaceClass = RoleService.class, version = "1.0.0")
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao dao;

    @Override
    public List<RoleDTO> listRole(int pageNum, int pageSize) {
        List<RoleDTO> roleDTOList = new ArrayList<>();

        List<Role> list = dao.listRole(pageNum, pageSize);

        for (Role role : list) {
            RoleDTO roleDTO = BeanUtil.copyProperties(role, RoleDTO.class);
            roleDTOList.add(roleDTO);
        }

        return roleDTOList;
    }

    @Override
    public RoleDTO getRoleById(int id) {
        Role role = dao.getRoleById(id);

        RoleDTO roleDTO = BeanUtil.copyProperties(role, RoleDTO.class);

        return roleDTO;
    }

    @Override
    public void addRole(RoleDTO roleDTO) {
        try {
            Role role = BeanUtil.copyProperties(roleDTO, Role.class);
            dao.addRole(role);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("添加角色失败",e);
        }
    }

    @Override
    public void delRole(int id) {
        try {
            dao.delRole(id);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("删除角色失败",e);
        }
    }

    @Override
    public void updateRole(RoleDTO roleDTO) {
        try {
            Role role = BeanUtil.copyProperties(roleDTO, Role.class);
            dao.updateRole(role);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("修改角色失败",e);
        }
    }
}